package com.baibei.order.settlement;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.baibei.basic.IPresenter;
import com.baibei.model.AddressInfo;
import com.baibei.model.BalanceInfo;
import com.baibei.model.BuyDirection;
import com.baibei.model.OrderInfo;
import com.baibei.module.AppRouter;
import com.baibei.module.BasicActivity;
import com.baibei.module.DateUtils;
import com.baibei.module.GlideApp;
import com.baibei.module.RechargeHelper;
import com.baibei.order.R;
import com.baibei.order.R2;
import com.baibei.ui.AppUI;
import com.baibei.widget.PriceTextView;
import com.makeramen.roundedimageview.RoundedImageView;
import com.rae.swift.Rx;
import com.rae.widget.dialog.DialogBuilder;
import com.rae.widget.dialog.IAppDialog;
import com.rae.widget.dialog.IAppDialogClickListener;

import butterknife.BindView;
import butterknife.OnClick;

import static com.baibei.ui.AppUI.dismiss;

/**
 * 补款取货
 * Created by ChenRui on 2017/8/11 0011 15:54.
 */
@Route(path = AppRouter.ROUTER_SETTLEMENT)
public class SettlementActivity extends BasicActivity implements SettlementContract.View {

    @BindView(R2.id.ll_empty_address_layout)
    TextView mEmptyAddressLayout;
    @BindView(R2.id.ll_address_info)
    LinearLayout mAddressInfoLayout;
    @BindView(R2.id.tv_rec_name)
    TextView mRecNameView;
    @BindView(R2.id.tv_phone)
    TextView mPhoneView;
    @BindView(R2.id.tv_address_name)
    TextView mAddressNameView;
    @BindView(R2.id.ll_address_layout)
    LinearLayout mAddressLayout;
    @BindView(R2.id.img_product)
    RoundedImageView mImgProductView;
    @BindView(R2.id.img_product_flag)
    ImageView mImgProductFlagView;
    @BindView(R2.id.tv_title)
    TextView mProductTitleView;
    @BindView(R2.id.tv_last_price)
    PriceTextView mLastPriceView;
    @BindView(R2.id.tv_quantity)
    TextView mQuantityView;
    @BindView(R2.id.tv_price_unit)
    TextView mPriceUnitView;
    @BindView(R2.id.tv_price)
    TextView mPriceView;
    @BindView(R2.id.tv_balance)
    TextView mBalanceView;
    @BindView(R2.id.tv_amount)
    TextView mAmountView;
    private SettlementContract.Presenter mPresenter;
    OrderInfo mOrderInfo;
    private AddressInfo mAddressInfo;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_settlement);
        mOrderInfo = getIntent().getParcelableExtra("orderInfo");
        mPresenter = inject(SettlementContract.Presenter.class);
        if (mOrderInfo != null) {
            //初始化数据
            onLoadOrderInfo(mOrderInfo);
        }
        mPresenter.start();
    }

    @Override
    public IPresenter getBasicPresenter() {
        return mPresenter;
    }

    @Override
    public void onEmptyAddress() {
        mEmptyAddressLayout.setVisibility(View.VISIBLE);
        mAddressLayout.setVisibility(View.GONE);
    }

    @Override
    public void onLoadDefaultAddress(AddressInfo addressInfo) {
        mAddressInfo = addressInfo;

        mRecNameView.setText(addressInfo.getReceiver());
        mPhoneView.setText(addressInfo.getMobile());
        mAddressNameView.setText(addressInfo.getFullAddress());

        mEmptyAddressLayout.setVisibility(View.GONE);
        mAddressLayout.setVisibility(View.VISIBLE);
    }

    @Override
    public OrderInfo getOrderInfo() {
        return mOrderInfo;
    }

    @Override
    public void onLoadOrderInfo(OrderInfo orderInfo) {
        mProductTitleView.setText(orderInfo.getName());
        mLastPriceView.setPrice(orderInfo.getLast()); // 市价
        mQuantityView.setText(getString(R.string.format_remain_count, orderInfo.getCount())); // 数量

        mPriceView.setText(Rx.formatPrice(orderInfo.getBuyMoney())); // 订金
        GlideApp.with(this)
                .load(orderInfo.getProductpic())
                .into(mImgProductView);

//        if (CONTRACT.XPT.name().equals(orderInfo.getArea())) {
//            mImgProductFlagView.setImageResource(R.mipmap.icon_flag_australia);
//        } else if (CONTRACT.XAU.name().equals(orderInfo.getArea())) {
//            mImgProductFlagView.setImageResource(R.mipmap.icon_flag_europe);
//        } else if (CONTRACT.XAG.name().equals(orderInfo.getArea())) {
//            mImgProductFlagView.setImageResource(R.mipmap.icon_flag_uk);
//        }
        //补款取货，结算价订货订单补款取货时，预订总金额=最新价格*预订数量，需补款=预订总金额—订金
        //预补款全额，跟预补款金额
        double allAmount = mOrderInfo.getBuyprice() * mOrderInfo.getCount();
        if (orderInfo.getBuydirection() == BuyDirection.DIRECTION_SETTLEMENT_PRICE) {
            allAmount = mOrderInfo.getLast() * mOrderInfo.getCount();
        }
        double amount = allAmount - mOrderInfo.getBuyMoney();
        mPriceUnitView.setText(Rx.formatPrice(allAmount));
        onLoadAmount(amount);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.resume();
    }

    @Override
    public void onLoadAmount(double amount) {
        mAmountView.setText(Rx.formatPrice(amount));
    }

    @Override
    public void onLoadBalanceFailed(String msg) {
        mBalanceView.setText("加载余额错误");
    }

    @Override
    public void onLoadBalanceInfo(BalanceInfo balanceInfo) {
        mBalanceView.setText(Rx.formatPrice(balanceInfo.getBalance()));
    }

    @Override
    public void onPaySuccess() {
        dismiss();
        mOrderInfo.setBuyMoney(mPresenter.getAmount());
        AppRouter.routeToSettlementStatus(this, mOrderInfo, DateUtils.formatDate(System.currentTimeMillis()), "申请中");
        setResult(RESULT_OK);
        finish();
    }

    @Override
    public void onPayFailed(String msg) {
        dismiss();
        new DialogBuilder(this).negativeButtonHidden().setMessage(msg).show();
    }

    @Override
    public String getAddressId() {
        return mAddressInfo == null ? null : mAddressInfo.getId();
    }

    @Override
    public void onNotMoney() {
        dismiss();
        new DialogBuilder(getContext())
                .setMessage("账户可用余额不足，前往充值？")
                .positiveButtonClickListener(new IAppDialogClickListener() {
                    @Override
                    public void onClick(IAppDialog dialog, int i) {
                        dialog.dismiss();
                        RechargeHelper.toRecharge(SettlementActivity.this, SettlementActivity.this);
                    }
                })
                .show();
    }

    @Override
    public void onTradeTimeout() {
        dismiss();
        new DialogBuilder(getContext())
                .setMessage("补款取货响应超时，请勿重复操作，是否现在前往订单中心？")
                .setCancelable(false)
                .setCanceledOnTouchOutside(false)
                .negativeButtonHidden()
                .positiveButtonText("立即前往")
                .setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialogInterface) {
                        AppRouter.routeToOrderCenter(SettlementActivity.this);
                        finish();
                        dismiss();
                    }
                })
                .show();
    }

    @OnClick(R2.id.ll_address_info)
    public void onAddressInfoClick() {
        AppRouter.routeToEditAddress(this, mAddressInfo, false);
    }

    @OnClick(R2.id.ll_empty_address_layout)
    public void onEmptyAddressClick() {
        AppRouter.routeToOrderAddress(this, true);
    }

    @OnClick(R2.id.btn_pay)
    public void onPayClick() {
        AppUI.loading(this, "正在处理..");
        mPresenter.pay();
    }

    @Override
    protected void onActivityResultOK(int requestCode, Intent data) {
        super.onActivityResultOK(requestCode, data);

        // 收货地址
        if (requestCode == AppRouter.REQ_ADDRESS && data != null) {
            mAddressInfo = data.getParcelableExtra("data");
            onLoadDefaultAddress(mAddressInfo);
        }
    }
}
